package com.cos.common;

import com.alibaba.fastjson.JSON;
import com.sun.istack.internal.localization.NullLocalizable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: COS
 * @time: 2021/11/17 14:20
 * @description: 统一一次处理器
 */
public class MyHandlerException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) {
        //打印错误信息
        ex.printStackTrace();
        System.out.println("handler:" + handler);
        ModelAndView mv = new ModelAndView();
        if ((request.getHeader("accept").indexOf("application/json") > -1 || (request
                .getHeader("X-Requested-With") != null && request.getHeader(
                "X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            // 如果是ajax请求，JSON格式返回
            try {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString("出错啦"));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (ex instanceof NumberFormatException) {
                mv.addObject("msg", "你操作有误稍后再试");
                mv.setViewName("error1");
            } else if (ex instanceof NullPointerException) {
                mv.addObject("msg", "您没有改操作的权限,请联系管理员");
                mv.setViewName("error2");
            } else {
                mv.addObject("msg", "你操作有病,去看医院");
                mv.setViewName("error1");
            }
        }
        return mv;
    }
}
